﻿#include "dlgmain.h"
#include "ui_dlgmain.h"

DlgMain::DlgMain(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DlgMain)
{
    ui->setupUi(this);

    //去掉窗口右上角的问号
    Qt::WindowFlags flags = this->windowFlags();
    flags |= Qt::WindowMinimizeButtonHint;
    flags &= ~Qt::WindowCloseButtonHint;
    this->setWindowFlags(flags);
    this->setFixedSize(320,278);

    // 1. 设置当前运行路径
    strRootDir = QCoreApplication::applicationDirPath();
    QDir::setCurrent(strRootDir);

    // 2. 托盘图标
    m_pSystemTray = new QSystemTrayIcon(this);
    m_pSystemTray->setToolTip(this->windowTitle());
    m_pSystemTray->setIcon(this->windowIcon());
    m_pSystemTray->show();
    connect(m_pSystemTray, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayicon_activated(QSystemTrayIcon::ActivationReason)));


    ui->textEdit->setReadOnly(true);
    m_bConnect = false;
    m_bIsStart = false;
    pr_setting = NULL;

    QSettings *g_pSettingCore = new QSettings("./Config/Robot.ini", QSettings::IniFormat);
    g_pSettingCore->setIniCodec("UTF-8");

    int nTimeout = g_pSettingCore->value("NetPipe/TimeOut").toInt();
    QString strIp = g_pSettingCore->value("NetPipe/Server").toString();
    int nEndPos = strIp.indexOf(":");
    m_strServerIp = strIp.left(nEndPos);
    nServerPort = strIp.right(strIp.length()-nEndPos-1).toInt();
    qDebug()<<"m_strServerIp"<<m_strServerIp<<nServerPort;

    pMySqlCtrl = new TMMySQLCtrl;

    m_pProcCmd = new QProcess();
    m_pProcCmd->setWorkingDirectory(strRootDir);
    connect(m_pProcCmd,SIGNAL(finished(int)),this,SLOT(slot_finished(int)));

    m_prTimer = new QTimer;
    connect(m_prTimer,SIGNAL(timeout()),this,SLOT(slot_start_netpipe()));
    m_prTimer->start(nTimeout);
}

DlgMain::~DlgMain()
{
    delete ui;
}

void DlgMain::init()
{
    QString strMac = getHostMacAddress().replace(":","");
    int m_port = pMySqlCtrl->getPortByRobotMac(strMac)+30000;

    QFile m_file(INI_PATH);
    if(m_file.exists()){
        m_file.open( QIODevice::WriteOnly | QIODevice::Truncate);
        m_file.close();
        showLog(QStringLiteral("NetPipe.ini已存在,清空完成！"));
    }
    //创建ini
    if(!pr_setting){
        pr_setting = new QSettings(INI_PATH, QSettings::IniFormat);
        pr_setting->setIniCodec("UTF-8");
    }
    pr_setting->beginGroup("common");
    pr_setting->setValue("server_addr", m_strServerIp);
    pr_setting->setValue("server_port", nServerPort);
    pr_setting->setValue("log_file", "./Log/NetPipe.log");
    pr_setting->setValue("log_level", "warn");
    pr_setting->setValue("log_max_days", 30);
    pr_setting->endGroup();
    pr_setting->beginGroup(strMac);
    pr_setting->setValue("type", "tcp");
    pr_setting->setValue("local_ip", "127.0.0.1");
    pr_setting->setValue("local_port", 8989);
    pr_setting->setValue("remote_port", m_port);
    pr_setting->endGroup();
    pr_setting->sync();
    showLog(QStringLiteral("创建并写入NetPipe.ini成功"));
}


void DlgMain::slot_start_netpipe()
{
    if(!m_bConnect){
        m_bConnect = pMySqlCtrl->connect_mysql(m_strServerIp);
        if(!m_bConnect){
            showLog(QStringLiteral("数据库连接失败，尝试重新连接..."));
        }else{
            init();
            showLog(QStringLiteral("数据库连接成功！"));
        }
        return;
    }
    if(m_bIsStart){
        return;
    }

    m_prTimer->stop();
    m_pProcCmd->start("NetPipe.exe -c ./Config/NetPipe.ini");
    m_bIsStart = true;
    showLog("NetPipe.exe start success!");
}


QString DlgMain:: getHostMacAddress()
{
    QList<QNetworkInterface> nets = QNetworkInterface::allInterfaces();// 获取所有网络接口列表
    int nCnt = nets.count();
    QString strMacAddr = "";
    for(int i = 0; i < nCnt; i ++)
    {
        // 如果此网络接口被激活并且正在运行并且不是回环地址，则就是我们需要找的Mac地址
        if(nets[i].flags().testFlag(QNetworkInterface::IsUp) && nets[i].flags().testFlag(QNetworkInterface::IsRunning) && !nets[i].flags().testFlag(QNetworkInterface::IsLoopBack))
        {
            strMacAddr = nets[i].hardwareAddress();
            break;
        }
    }
    return strMacAddr;
}

void DlgMain::showLog(QString strLog)
{
    ui->textEdit->append(strLog);
}

void DlgMain::slot_finished(int exitCode)
{
    showLog(QString("NetPipe.exe exit:%1").arg(exitCode));
    m_bIsStart = false;
    m_prTimer->start(10000);
}


void DlgMain::on_btn_hide_clicked()
{
    this->hide();
}

void DlgMain::on_btn_exit_clicked()
{
    int nLoop = 80;
    while(nLoop>0){
        nLoop -= 1;
        QCoreApplication::processEvents();
        QThread::msleep(10);
    }
    m_pProcCmd->kill();
    this->close();
}

void DlgMain::trayicon_activated(QSystemTrayIcon::ActivationReason reason)
{
    if( reason == QSystemTrayIcon::DoubleClick || reason == QSystemTrayIcon::Context ){
        if( this->isVisible() ){
            this->hide();
            qDebug()<<"托盘显示提示信息";
            //托盘显示提示信息
            m_pSystemTray->showMessage(QStringLiteral("Tami.RobotCore信息:"), QStringLiteral("窗口已经隐藏..."), QSystemTrayIcon::Information, 1000);
        }else{
            this->show();
            m_pSystemTray->showMessage(QStringLiteral("Tami.RobotCore信息:"), QStringLiteral("窗口已经显示..."), QSystemTrayIcon::Information, 1000);
        }
    }

}
